package com.another.gateway.util;

import com.alibaba.fastjson.JSON;
import com.another.common.utils.common.EmptyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AsyncLog {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ApiPath apiPath;


//    @Async
    public void saveLog(HttpServletRequest request,String requestId) {

        logger.info("++++++++++++++++++++++++++++++开始保存日志到数据库");

        try {

            //截取url
            String baseUrl = request.getRequestURI();
            String url = baseUrl.substring(baseUrl.indexOf("/", 1), baseUrl.length());


            if (!apiPath.getLogPath().contains(url)) {
                return;
            }

            //获取header里面的值
            Map<String, String> map = new HashMap<String, String>();
            Enumeration headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }

            logger.info(JSON.toJSONString(map));

            //获取请求参数
            String parameter = "";
            try {
                BufferedReader reader = request.getReader();
                char[] buf = new char[512];
                int len = 0;
                StringBuffer contentBuffer = new StringBuffer();
                while ((len = reader.read(buf)) != -1) {
                    contentBuffer.append(buf, 0, len);
                }
                parameter = contentBuffer.toString();

                //输出请求参数
                logger.info("请求参数是:" + parameter);

            } catch (Exception e) {
                logger.info(request.getRequestURL() + "出异常了, 异常是:" + e.getMessage());
                e.printStackTrace();
                parameter = "";
            }


            //获取IP
            String ip = "";
            if (EmptyUtil.isEmpty(request.getHeader("X-Real-IP"))) {
                ip = request.getRemoteHost();    //请求ip
            } else {
                ip = request.getHeader("X-Real-IP");
            }


            logger.info("++++++++++++++++++++++++++++++保存日志到数据库成功");
        } catch (Exception e) {
            logger.info("++++++++++++++++++++++++++++++保存日志到数据库失败", e);
            e.printStackTrace();
            logger.info(e.getMessage(), e);
        }


    }
}